<?php

namespace App\Repositories\Admin;

use App\BaseRepository;
use App\Model\ResourceTable;
use App\Model\SysRegion;
use App\Model\WineProductChateauRelation;
use App\Model\WineProductCuisineRelation;
use App\Model\WineProductDealerRelation;
use App\Model\WineProductDeployment;
use App\Model\WineProductImporterRelation;
use App\Model\WineProductRelation;
use App\Model\WineProductSceneRelation;
use App\Model\WineProductUserTag;
use Illuminate\Support\Facades\DB;

class WineProductRepository extends BaseRepository
{
    //模型名称
    protected $modelName = "App\Model\WineProduct";

    protected $appendCreatorAndUpdater = true;

    protected $appendUserId = true;

    protected $allowApiMethod = ['index','show','store','update','destroy','destroyBatch',"simpleList"];

    protected function simpleListQuery()
    {
        return DB::table($this->query()->getTable())->whereNull('deleted_at')->where('online','=','yes');
    }

    protected function simpleListFiled()
    {
        return ['id','name','chname'];
    }

    protected function beforeListShow($model)
    {
        return $model->orderBy('weight','desc')->orderBy('created_at','desc');
    }

    protected function getShowRespondData($model)
    {
        return $model->load('covers','drink','judge','technique','score','chateau','chateau.produce','country',
            'subdivision','region','scenes','blendDeployment','relationProducts','relationChateaus',
            'score.sameScores','relationImporters','relationDealers','cuisines','scenes','wineTastes',
            'wineGrading','userTags');
    }

    protected function appendStoreFillData()
    {
        $attr['state'] = 'draft';
        if ($this->loginUser->userType == "admin"){
            $attr['state'] = "publish";
        }
        if ($this->loginUser->userType == "editor"){
            $attr['state'] = "pending";
        }
        return $attr;
    }

    protected function commonRules()
    {
        return [
            'name' => 'required',
            'chname' => 'required',
            'chateau_id' => 'required',
            'vintage' => 'required',
            'country_id' => 'required',
            //'subdivision_id' => 'required',
            'region_id' => 'required',
            'productCode' => 'required|max:2',
            'deployment' => 'required',
        ];
    }

    private function checkDeploymentScale()
    {
        if ($this->request->has('deployment_graperies') && $this->request->input('deployment') == "blend"){
            $graperies = $this->request->input('deployment_graperies');
            if (count($graperies ) < 2){
                $this->error = '最少2种';
                return false;
            }
            if (count($graperies ) > 20){
                $this->error = '最多20种';
                return false;
            }
            $c = 0;
            foreach ($graperies  as $item){
                $c +=$item['scale'];
            }

            if ($c>100) {
                $this->error = '葡萄调配比例不能超过100！';
                return false;
            }
        }
        return true;

    }

    protected function processStoreValidate()
    {
        $bool = DB::table('wine_product')->where('productCode','=',$this->request->input('productCode'))
            ->whereNull("deleted_at")
            ->where('chateau_id','=',$this->request->input('chateau_id'))->count()>0?true:false;
        if($bool) {
            $this->error = '葡萄酒编码已被使用';
            return false;
        }

        $importers = $this->request->input('importers');

        if ($importers) {
            if (count($importers) > 10){
                $this->error = '进口商最多选择10个';
                return false;
            }
        }

        return $this->checkDeploymentScale();
    }

    protected function processUpdateValidate($id)
    {
        $bool = DB::table('wine_product')->where('productCode','=',$this->request->input('productCode'))
            ->whereNull("deleted_at")
            ->where('chateau_id','=',$this->request->input('chateau_id'))
            ->where('id','<>',$id)
            ->count()>0?true:false;
        if($bool) {
            $this->error = '葡萄酒编码已被使用';
            return false;
        }
        return $this->checkDeploymentScale();

    }

    //保存封面 cover_ids
    private function saveCovers($model)
    {
        if ($this->request->has('cover_ids')) {
            $ids = $this->request->input('cover_ids');

            $rows = $ids?explode(',',$ids) : [];

            $db = DB::table('sys_resource_table')->where('obj_id','=',$model->id)
                ->where('obj_type','=','product_cover');

            $o_ids = $db->pluck('resource_id')->toArray();
            

            $db->whereIn('resource_id',array_diff($o_ids,$rows))->delete();

            $rows = array_diff($rows,$o_ids);

            foreach ($rows as $row) {
                $AR = new ResourceTable();
                $AR->obj_id = $model->id;
                $AR->resource_id = $row;
                $AR->user_id = $this->loginUser->id;
                $AR->obj_type = 'product_cover';
                $AR->save();
            }
            return true;
        }
        return false;
    }

    //调配混酿 deployment_graperies
    private function saveDeployment($model)
    {
        if($this->request->exists('deployment_graperies')) {
            DB::table('wine_product_deployment')->where('product_id','=',$model->id)->delete();
            $rows = $this->request->input('deployment_graperies');

            if(count($rows)>0) {
                foreach ($rows as $row) {
                    if (isset($row['name']) && $row['name'] && isset($row['scale'])) {
                        $m = new WineProductDeployment();
                        $m->product_id = $model->id;
                        $m->name = $row['name'];
                        $m->scale = $row['scale'];
                        if (isset($row['harvestDate'])){
                            $m->harvestDate = $row['harvestDate'];
                        }
                        $m->user_id = $this->loginUser->id;
                        $m->save();
                    }
                    
                }
                return true;
            }
        }

        return false;
    }

    //关联葡萄酒 product_relation_ids
    private function saveProductRelation($model)
    {
        if ($this->request->has('product_relation_ids')) {
            $ids = $this->request->input('product_relation_ids');

            $rows = $ids?explode(',',$ids) : [];

            $db = DB::table('wine_product_relation')->where('product_id','=',$model->id);

            $o_ids = $db->pluck('obj_id')->toArray();

            $db->whereIn('obj_id',array_diff($o_ids,$rows))->delete();

            $rows = array_diff($rows,$o_ids);

            foreach ($rows as $row) {
                $m = new WineProductRelation();
                $m->product_id = $model->id;
                $m->obj_id = $row;
                $m->user_id = $this->loginUser->id;
                $m->save();

            }
            return true;
        }
        return false;
    }

    //关联酒庄 chateau_relation_ids
    private function saveChateauRelation($model)
    {
        if ($this->request->has('chateau_relation_ids')) {
            $ids = $this->request->input('chateau_relation_ids');

            $rows = $ids?explode(',',$ids) : [];

            $db = DB::table('wine_product_chateau_relation')->where('product_id','=',$model->id);

            $o_ids = $db->pluck('obj_id')->toArray();

            $db->whereIn('obj_id',array_diff($o_ids,$rows))->delete();

            $rows = array_diff($rows,$o_ids);

            foreach ($rows as $row) {
                $m = new WineProductChateauRelation();
                $m->product_id = $model->id;
                $m->obj_id = $row;
                $m->user_id = $this->loginUser->id;
                $m->save();

            }
            return true;
        }
        return false;
    }

    //关联地区
    private function saveSubdivision($model)
    {
        if($region = SysRegion::find($model->region_id)){
            $model->subdivision_id = $region->subdivision_id;
            $model->save();
        }
    }

    protected function commonSave($model)
    {
        $this->saveCovers($model);
        $this->saveDeployment($model);
        $this->saveScene($model);
        $this->saveChateauRelation($model);
        $this->saveProductRelation($model);
        $this->saveSubdivision($model);
        $this->saveImporter($model);
        $this->saveUserTag($model);
        $this->saveCuisine($model);

        if ($model->chateau){
            $model->chateauName = $model->chateau->chname;
            $model->save();
        }
    }
    //消费场景  scene_ids
    private function saveScene($model)
    {
        if ($this->request->exists('scene_ids')) {
            $rows = $this->request->input('scene_ids');

            DB::table('wine_product_scene_relation')->where('product_id','=',$model->id)->delete();

            foreach ($rows as $row) {
                if (isset($row['scene_one_id'])){
                    $m = new WineProductSceneRelation();
                    $m->fill($row);
                    $m->product_id = $model->id;
                    $m->user_id = $this->loginUser->id;
                    $m->save();
                }

            }
            return true;
        }
        return false;
    }
    //用户标签
    protected function saveUserTag($model)
    {
        if ($this->request->has('user_tags')) {
            $user_tags = $this->request->input('user_tags',[]);

            DB::table('wine_product_user_tags')->where('product_id','=',$model->id)->delete();

            foreach ($user_tags as $row) {
                $m = new WineProductUserTag();
                $m->auth= isset($row['auth'])?$row['auth']:"";
                $m->sex= isset($row['sex'])?$row['sex']:"";
                $m->age= isset($row['age'])?$row['age']:"";
                $m->product_id = $model->id;
                $m->save();
            }
            return true;
        }
        return false;

    }
    //菜系选择
    protected function saveCuisine($model)
    {
        if ($this->request->has('wine_cuisines')) {
            $user_tags = $this->request->input('wine_cuisines',[]);

            DB::table('wine_product_cuisine_relations')->where('product_id','=',$model->id)->delete();

            foreach ($user_tags as $row) {
                if (isset($row['wine_cuisines_id'])){
                    if($cuisine = DB::table('wine_cuisines')->whereNull('deleted_at')->where('id','=',$row['wine_cuisines_id'])->first()){
                        $m = new WineProductCuisineRelation();
                        $m->fill($row);
                        $m->product_id = $model->id;
                        $m->wine_cuisines_id = $row['wine_cuisines_id'];
                        $m->name = $cuisine->name;
                        $m->icon = $cuisine->icon;
                        $m->save();
                    }
                }
            }
            return true;
        }
        return false;
    }

    protected function destroyValidate($id)
    {
        $c = DB::table('wine_focus_picture')->where('obj_id','=',$id)->where('type','=','product')
            ->whereNull('deleted_at')->count();

        if($c>0) {
            $this->error = "此产品已关联焦点图";
            return false;
        }

        $c = DB::table('orders')->where('product_id','=',$id)->whereNull('deleted_at')->count();

        if($c>0) {
            $this->error = "此产品已有相关订单，不可删除";
            return false;
        }

        return true;
    }

    //保存进口商和经销商
    protected function  saveImporter($model)
    {
        $bool = $this->request->exists('importers');
        if ($bool) {
            $importers = $this->request->input('importers');
            $dealers = $this->request->input('dealers');

            DB::table('wine_product_importer_relations')->where('product_id','=',$model->id)->delete();
            DB::table('wine_product_dealer_relations')->where('product_id','=',$model->id)->delete();

            if ($importers) {
                foreach ($importers as $v){
                    $m = new WineProductImporterRelation();
                    $m->product_id = $model->id;
                    $m->importer_id = $v;
                    $m->user_id = $this->loginUser->id;
                    $m->save();
                }
            }

            if ($dealers) {
                foreach ($dealers as $v){
                    if (isset($v['id']) && isset($v['show'])){
                        $m = new WineProductDealerRelation();
                        $m->product_id = $model->id;
                        $m->dealer_id = $v['id'];
                        $m->show = $v['show'];
                        $m->user_id = $this->loginUser->id;
                        $m->save();
                    }

                }
            }

        }
        return true;
    }

}